package com.example.chatai.Config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisor;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisorChain;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.core.Ordered;
import reactor.core.publisher.Flux;

/**
 * 自定义日志 Advisor，兼容 Spring AI 1.0.1 的 Advisors API。
 * 实现 CallAdvisor 与 StreamAdvisor，分别拦截同步与流式调用。
 */
public class CustomLoggingAdvisor implements CallAdvisor, StreamAdvisor, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(CustomLoggingAdvisor.class);

    @Override
    public ChatClientResponse adviseCall(ChatClientRequest chatClientRequest, CallAdvisorChain chain) {
        // 请求前日志
        logger.info("[CustomLoggingAdvisor] adviseCall request = {}", chatClientRequest);
        // 调用下一个节点（最终会到达真实的模型调用）
        ChatClientResponse response = chain.nextCall(chatClientRequest);
        // 响应后日志
        logger.info("[CustomLoggingAdvisor] adviseCall response = {}", response);
        return response;
    }

    @Override
    public Flux<ChatClientResponse> adviseStream(ChatClientRequest chatClientRequest, StreamAdvisorChain chain) {
        // 流式请求前日志
        logger.info("[CustomLoggingAdvisor] adviseStream request = {}", chatClientRequest);
        // 继续链路并在流中追加日志
        return chain.nextStream(chatClientRequest)
                .doOnNext(resp -> logger.info("[CustomLoggingAdvisor] stream chunk = {}", resp))
                .doOnComplete(() -> logger.info("[CustomLoggingAdvisor] stream completed"))
                .doOnError(err -> logger.error("[CustomLoggingAdvisor] stream error", err));
    }

    // 控制执行顺序（数值越小优先级越高）
    @Override
    public int getOrder() {
        return 0;
    }

    // 可选：为该 Advisor 提供一个名称（部分工具/日志会展示）
    @Override
    public String getName() {
        return "custom-logging-advisor";
    }
}